package com.jielin.handling.controller.checkbody;

import com.alibaba.fastjson.JSONObject;
import com.jielin.handling.Annotation.MyPower;
import com.jielin.handling.bean.AppResult;
import com.jielin.handling.entity.checkbody.TBody;
import com.jielin.handling.entity.checkbody.TBodyPic;
import com.jielin.handling.exception.ResultEnum;
import com.jielin.handling.service.checkbody.CheckBodyService;
import com.jielin.handling.util.ConstantUtil;
import com.jielin.handling.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

/**
 * Created by wangjienice on 2019/3/18.
 */
@CrossOrigin
@RestController
@RequestMapping("/checkBody/")
@Slf4j
@MyPower(name = "嫌疑人人身检查模块", url = "/checkBody")
public class CheckBodyController {

    @Autowired
    private CheckBodyService checkBodyService;

    /**
     * 新增人身检查记录
     */
    @MyPower(name = "新增人身检查记录", url = "/addCheck")
    @RequestMapping("addCheck")
    public AppResult addCheck(@RequestBody TBody tBody) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        log.info("tBody:{}", JSONObject.toJSONString(tBody));
        checkBodyService.delectCheckBody(tBody.getSuspectId());
        int value = checkBodyService.insert(tBody);
        if (value > 0) {
            date.put("value", 1);
            appResult.setCode(200);
            appResult.setMsg("新增人身检查记录成功!");
            appResult.setData(date);
        } else {
            date.put("Value", 0);
            appResult.setCode(-1);
            appResult.setMsg("新增人身检查记录失败!");
            appResult.setData(date);
        }
        return appResult;
    }

    /**
     * 新增嫌疑人伤口照片信息
     */
//    @MyPower(name = "新增嫌疑人伤口照片信息", url = "/saveWoundPhoto")
//    @RequestMapping("saveWoundPhoto")
//    public AppResult saveWoundPhoto(MultipartFile file, String suspectId, String fileString) {
//        AppResult appResult=new AppResult();
//        JSONObject date=new JSONObject();
//        log.info("file:{}",JSONObject.toJSONString(file));
//        log.info("suspectId:{}",JSONObject.toJSONString(suspectId));
//        log.info("fileString:{}",JSONObject.toJSONString(fileString));
//        // 获取当前系统时间毫秒数
//        String trueFileName = String.valueOf(System.currentTimeMillis());
//        //设置文件的路径并存储到指定文件夹
//        String folderPath = ConstantUtil.PHOTO_PATH+"suspect"+File.separatorChar+"wound"+File.separatorChar;
//        //创建文件夹
//        File folderFile=new File(folderPath);
//        if(!folderFile.exists()){
//            folderFile.mkdirs();
//        }
//        try {
//            if (file != null) {
//                // 文件原名称
//                String fileName = file.getOriginalFilename();
//                //获取文件类型
//                String fileType = fileName.substring(fileName.lastIndexOf("."));
//                // 拼接文件路径
//                String path=folderPath+trueFileName+fileType;//磁盘存储路径
//                String filePath=File.separatorChar+"suspect"+File.separatorChar+"wound"+File.separatorChar+trueFileName+fileType;//数据库存储路劲
//                FileOutputStream out = new FileOutputStream(path);
//                out.write(file.getBytes());
//                out.flush();
//                out.close();
//                //设置图片路径
//                TBodyPic tBodyPic=new TBodyPic();
//                tBodyPic.setPicUrl(filePath);
//                tBodyPic.setSuspectId(suspectId);
//                String id= StringUtil.generatorUUID();
//                tBodyPic.setId(id);
//                //返回给前台的图片路径，nginx地址，端口，，nginx映射，数据库存储路径
//                String returnPath=ConstantUtil.SERVER_URL+filePath;
//                int value=checkBodyService.saveWoundPhoto(tBodyPic);
//                if(value>0){
//                    date.put("value",1);
//                    date.put("returnPath",returnPath);
//                    date.put("id",id);
//                    appResult.setCode(200);
//                    appResult.setMsg("新增嫌疑人伤口照片信息成功!");
//                    appResult.setData(date);
//
//                }else{
//                    date.put("value",0);
//                    date.put("path",value);
//                    appResult.setCode(-1);
//                    appResult.setMsg("新增嫌疑人伤口照片信息失败!");
//                    appResult.setData(date);
//                }
////                response.setContentType("text/html");
////                response.getWriter().write(JSONObject.toJSONString(appResult));
//                return appResult;
//                //return appResult;
//            }else if (fileString != null && fileString != ""){//// 解码Base64上传图片
//               // String truefileType=fileString.substring(fileString.indexOf("/")+1,fileString.indexOf(";"));// 获取图片类型
//                String fileType = ".png" ;
//                String path=folderPath+trueFileName+fileType;//磁盘存储地址
//                String filePath=File.separatorChar+"suspect"+File.separatorChar+"wound"+File.separatorChar+trueFileName+fileType;//数据库存储地址
//                //Base64解码
//                BASE64Decoder decoder = new BASE64Decoder();
//                String base64String =fileString.substring(fileString.indexOf(",")+1);// 去掉头部（不能解析）
//                log.info("Base64解码后:\n"+base64String);
//                byte[] b = decoder.decodeBuffer(base64String);
//                for (int i = 0; i < b.length; ++i) {
//                    if (b[i] < 0) {//调整异常数据
//                        b[i] += 256;
//                    }
//                }
//                TBodyPic tBodyPic=new TBodyPic();
//                tBodyPic.setPicUrl(filePath);
//                tBodyPic.setSuspectId(suspectId);
//                String id=StringUtil.generatorUUID();
//                tBodyPic.setId(id);
//                FileOutputStream out = new FileOutputStream(path);
//                out.write(b);
//                out.flush();
//                out.close();
//                int value=checkBodyService.saveWoundPhoto(tBodyPic);
//                //返回给前台的图片路径，nginx地址，端口，，nginx映射，数据库存储路径
//                String returnPath=ConstantUtil.SERVER_URL+filePath;
//                if(value>0) {
//                    date.put("id",id);
//                    date.put("value",1);
//                    date.put("returnPath",returnPath);
//                    appResult.setCode(200);
//                    appResult.setMsg("新增嫌疑人伤口照片信息成功!");
//                    appResult.setData(date);
//                }else{
//                    date.put("value",0);
//                    appResult.setCode(-1);
//                    appResult.setMsg("新增嫌疑人伤口照片信息失败!");
//                    appResult.setData(date);
//                }
//                return appResult;
//            }
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
//        date.put("value",0);
//        appResult.setCode(-1);
//        appResult.setMsg("新增嫌疑人伤口照片信息失败!");
//        appResult.setData(date);
//        return appResult;
//    }

    /**
     * 根据嫌疑人id和嫌疑人照片路径更新嫌疑人伤口信息
     */
    @MyPower(name = "根据嫌疑人id和嫌疑人照片路径更新嫌疑人伤口信息", url = "/updateWound")
    @RequestMapping("updateWound")
    public AppResult updateWound(@RequestBody TBodyPic tBodyPic) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        log.info("tBodyPic:{}", JSONObject.toJSONString(tBodyPic));
        int value = checkBodyService.updateWound(tBodyPic);
        if (value > 0) {
            date.put("value", 1);
            appResult.setCode(200);
            appResult.setMsg("更新嫌疑人伤口信息成功!");
            appResult.setData(date);
        } else {
            date.put("Value", 0);
            appResult.setCode(-1);
            appResult.setMsg("更新嫌疑人伤口信息失败!");
            appResult.setData(date);
        }
        return appResult;
    }

    /**
     * 嫌疑人伤口照片是否删除状态变化
     */
    @MyPower(name = "嫌疑人伤口照片是否删除状态变化", url = "/updateWoundPhoto")
    @RequestMapping("updateWoundPhoto")
    public AppResult updateWoundPhoto(String id) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        log.info("id:{}", JSONObject.toJSONString(id));
        int value = checkBodyService.updateWoundPhoto(id);
        if (value > 0) {
            date.put("value", 1);
            appResult.setCode(200);
            appResult.setMsg("嫌疑人伤口照片删除成功!");
            appResult.setData(date);
        } else {
            date.put("Value", 0);
            appResult.setCode(-1);
            appResult.setMsg("嫌疑人伤口照片删除失败!");
            appResult.setData(date);
        }
        return appResult;
    }


    /**
     * 嫌疑人所有伤口图片(只查询状态为0未删除的照片)
     */
    @MyPower(name = "嫌疑人所有伤口图片(只查询状态为0未删除的照片)", url = "/selectAllPic")
    @RequestMapping("selectAllPic")
    public AppResult selectAllPic(String suspectId) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        log.info("suspectId:{}", JSONObject.toJSONString(suspectId));
        List<TBodyPic> list = checkBodyService.selectAllPic(suspectId);
        date.put("list", list);
        appResult.setCode(200);
        appResult.setMsg("查询嫌疑人伤口照片成功!");
        appResult.setData(date);
        return appResult;
    }

    /**
     * 根据id查询嫌疑人人身检查信息
     */
    @MyPower(name = "根据id查询嫌疑人人身检查信息", url = "/selectById")
    @RequestMapping("selectById")
    public AppResult selectById(String suspectId) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        log.info("suspectId:{}", JSONObject.toJSONString(suspectId));
        List<TBodyPic> tBody = checkBodyService.selectById(suspectId);
        date.put("tBody", tBody);
        appResult.setCode(200);
        appResult.setMsg("查询嫌疑人人身检查信息成功!");
        appResult.setData(date);

        return appResult;
    }

    @MyPower(name = "新增嫌疑人伤口照片信息", url = "/saveWoundPhoto")
    @RequestMapping("/saveWoundPhoto")
    public AppResult saveWoundPhoto2(MultipartFile file, String suspectId, String fileString) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        log.info("file:" + file);
        log.info("suspectId:" + suspectId);
        log.info("fileString:" + fileString);
        if (ConstantUtil.XSKYRESTORAGE) {
            if (file == null && fileString == null) {
                date.put("data", "没有相关的文件");
                return AppResult.builder().setCode(ResultEnum.FAIL.getCode()).setMsg("添加警告！").setData(date);
            }
            TBodyPic tBodyPic = checkBodyService.saveWoundPhoto2(file, suspectId, fileString);
            if (tBodyPic != null) {
                date.put("path", tBodyPic.getPicUrl());
                date.put("id", tBodyPic.getId());
                return AppResult.builder().setCode(ResultEnum.SUCCESS.getCode()).setMsg("文件上传成功！").setData(date);
            } else {
                return AppResult.builder().setCode(ResultEnum.FAIL.getCode()).setMsg("文件上传失败！(可能原因：1.上传文件为空)");
            }
        } else {
            String trueFileName = String.valueOf(System.currentTimeMillis());
            //设置文件的路径并存储到指定文件夹
            String folderPath = ConstantUtil.PHOTO_PATH + "suspect" + File.separatorChar + "wound" + File.separatorChar;
            //创建文件夹
            File folderFile = new File(folderPath);
            if (!folderFile.exists()) {
                folderFile.mkdirs();
            }
            try {
                if (file != null) {
                    // 文件原名称
                    String fileName = file.getOriginalFilename();
                    //获取文件类型
                    String fileType = fileName.substring(fileName.lastIndexOf("."));
                    // 拼接文件路径
                    String path = folderPath + trueFileName + fileType;//磁盘存储路径
                    String filePath = File.separatorChar + "suspect" + File.separatorChar + "wound" + File.separatorChar + trueFileName + fileType;//数据库存储路劲
                    FileOutputStream out = new FileOutputStream(path);
                    out.write(file.getBytes());
                    out.flush();
                    out.close();
                    //设置图片路径
                    TBodyPic tBodyPic = new TBodyPic();
                    tBodyPic.setPicUrl(filePath);
                    tBodyPic.setSuspectId(suspectId);
                    String id = StringUtil.generatorUUID();
                    tBodyPic.setId(id);
                    //返回给前台的图片路径，nginx地址，端口，，nginx映射，数据库存储路径
                    String returnPath = ConstantUtil.SERVER_URL + filePath;
                    int value = checkBodyService.saveWoundPhoto(tBodyPic);
                    if (value > 0) {
                        date.put("value", 1);
                        date.put("returnPath", returnPath);
                        date.put("id", id);
                        appResult.setCode(200);
                        appResult.setMsg("新增嫌疑人伤口照片信息成功!");
                        appResult.setData(date);

                    } else {
                        date.put("value", 0);
                        date.put("path", value);
                        appResult.setCode(-1);
                        appResult.setMsg("新增嫌疑人伤口照片信息失败!");
                        appResult.setData(date);
                    }
//                response.setContentType("text/html");
//                response.getWriter().write(JSONObject.toJSONString(appResult));
                    return appResult;
                    //return appResult;
                } else if (fileString != null && fileString != "") {//// 解码Base64上传图片
                    // String truefileType=fileString.substring(fileString.indexOf("/")+1,fileString.indexOf(";"));// 获取图片类型
                    String fileType = ".png";
                    String path = folderPath + trueFileName + fileType;//磁盘存储地址
                    String filePath = File.separatorChar + "suspect" + File.separatorChar + "wound" + File.separatorChar + trueFileName + fileType;//数据库存储地址

                    //Base64解码
                    BASE64Decoder decoder = new BASE64Decoder();
                    String base64String = fileString.substring(fileString.indexOf(",") + 1);// 去掉头部（不能解析）
                    log.info("Base64解码后:\n" + base64String);
                    byte[] b = decoder.decodeBuffer(base64String);
                    for (int i = 0; i < b.length; ++i) {
                        if (b[i] < 0) {//调整异常数据
                            b[i] += 256;
                        }
                    }
                    TBodyPic tBodyPic = new TBodyPic();
                    tBodyPic.setPicUrl(filePath);
                    tBodyPic.setSuspectId(suspectId);
                    String id = StringUtil.generatorUUID();
                    tBodyPic.setId(id);
                    FileOutputStream out = new FileOutputStream(path);
                    out.write(b);
                    out.flush();
                    out.close();
                    int value = checkBodyService.saveWoundPhoto(tBodyPic);
                    //返回给前台的图片路径，nginx地址，端口，，nginx映射，数据库存储路径
                    String returnPath = ConstantUtil.SERVER_URL + filePath;
                    if (value > 0) {
                        date.put("id", id);
                        date.put("value", 1);
                        date.put("returnPath", returnPath);
                        appResult.setCode(200);
                        appResult.setMsg("新增嫌疑人伤口照片信息成功!");
                        appResult.setData(date);
                    } else {
                        date.put("value", 0);
                        appResult.setCode(-1);
                        appResult.setMsg("新增嫌疑人伤口照片信息失败!");
                        appResult.setData(date);
                    }
                    return appResult;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            date.put("value", 0);
            appResult.setCode(-1);
            appResult.setMsg("新增嫌疑人伤口照片信息失败!");
            appResult.setData(date);
            return appResult;
        }
    }
}